
var app = require('express')(); //服务端框架
var http = require('http').createServer(app);
var io = require('socket.io')(http)

let roomName = ['房间1', '房间2', '房间3']//应从数据库获取

// const adminNamespace1 = io.of("/房间1");
// const adminNamespace2 = io.of("/房间2");



//路由：'/' 访问'/'时被调用
app.get('/', (req, res) => {

  res.sendFile(__dirname + '/index.html')
})

// io.on('connection', (socket) => {
//   let name = socket.handshake.query.name;
//   socket.broadcast.emit('hi', name + '已连接')//广播 除自己客户端外)
//   console.log('io')
// })

io.on('connection', (socket) => {
  console.log('用户已连接')
  //let name = socket.handshake.query.name;
  //socket.broadcast.emit('hi', name + '已连接')//广播 除自己客户端外)

  let name = socket.handshake.query.name;


  //socket.join(roomName);

  //console.log(socket.rooms); // Set { <socket.id>, "room1" }

  roomName.forEach(function (ele) {
    socket.on(ele, (msg) => {
      io.emit(ele, msg) //默认发给所有客户端
      console.log('message: ' + msg.message + msg.name)
    })

  })



  socket.on('disconnect', () => {
    console.log('用户已断开连接')
  })
})

// adminNamespace2.on('connection', (socket) => {
//   console.log('房间2用户已连接')
//   socket.on('chat message', (msg) => {
//     //socket.broadcast.emit('hi', '用户已连接')
//     adminNamespace2.emit('chat message', msg) //默认发给所有客户端
//     console.log('message: ' + msg)
//   })

//   socket.on('disconnect', () => {
//     console.log('用户已断开连接')
//   })
// })

// io.on('connection', (socket) => {
//   console.log('用户已连接')
//   console.log(socket.handshake.query.token)
//   socket.broadcast.emit('hi', '用户已连接')//广播 除自己客户端外

//   socket.on('chat message', (msg) => {
//     //socket.broadcast.emit('hi', '用户已连接')
//     io.emit('chat message', msg) //默认发给所有客户端
//     console.log('message: ' + msg)
//   })

//   socket.on('disconnect', () => {
//     console.log('用户已断开连接')
//   })
// })






http.listen(3000, () => {
  console.log('正在监听3000')
})